using UnityEngine;
using System.Collections;

public class FlyingEgg : MonoBehaviour {
	private float virtGrav;
	private float height;
	private float bottomHeight;
	private float vZero;
	private Vector3 spherePosition;
	public GameObject realEgg;
	public int count;
	
	public void Start(){
		gameObject.transform.Rotate(new Vector3(0,count*120,0));
		vZero = 0.15f;
		virtGrav = 0.01f;
		bottomHeight = Vector3.Distance(gameObject.transform.position, GameObject.Find("Sphere").gameObject.transform.position);
		spherePosition = GameObject.Find("Sphere").transform.position; //Vector3.zero
	}
	
	public void Update(){
		Vector3 planetNormal = (gameObject.transform.position - spherePosition).normalized;
		
		Vector3 a = gameObject.transform.position;
		gameObject.transform.Translate(new Vector3(0, 0, 0.1f));
		Vector3 b = gameObject.transform.position;
		gameObject.transform.Translate(new Vector3(0, 0, -0.1f));
			
		Vector3 positionDiff = a - spherePosition;
		
		Vector3 playerHeading = (a - b).normalized;
		Vector3 axis = Vector3.Cross(playerHeading, positionDiff);
		gameObject.transform.RotateAround(spherePosition, axis, 30f * Time.deltaTime);
		
		gameObject.transform.Translate(planetNormal * vZero);
		vZero -= virtGrav;
		
		if(Vector3.Distance(gameObject.transform.position,spherePosition) <= bottomHeight){
			transform.position = spherePosition + planetNormal*bottomHeight;
			Instantiate(realEgg,gameObject.transform.position,gameObject.transform.rotation);
			Destroy(gameObject);
		}
		
		
	}
}
